import Request from "@/common/utils/request/index";
import { router } from "@/router/index";
import {
  GetUserInfoModel,
  LoginParams,
  LoginResultModel,
} from "@/types/model/user.model";
import { useUserStore } from "@/store/modules/user.store";
import { AuthStorage } from "@/storage/auth.storage";
import { LOGIN_PAGE } from "@/router/routerNames/index";

enum Api {
  Login = "/jeecgboot/sys/login",
  getInputCode = "/jeecgboot/sys/randomImage",
  GetUserInfo = "/jeecgboot/sys/user/getUserInfo",
  Logout = "/jeecgboot/sys/logout",
  GetUserPermissionByToken = "/jeecgboot/pos/permission/getUserPermissionByToken",
}

export function getCodeInfo(currdatetime: any) {
  let url = Api.getInputCode + `/${currdatetime}`;
  return Request.getInstance().send<string>({
    url: url,
    method: "GET",
  });
}

export function loginApi(params: LoginParams) {
  return Request.getInstance().send<LoginResultModel>({
    url: Api.Login,
    method: "POST",
    data: params,
  });
}

export function logoutApi() {
  return Request.getInstance().send<string>({
    url: Api.Logout,
    method: "POST",
  });
}

export function getUserInfo() {
  return Request.getInstance()
    .send<GetUserInfoModel>({
      url: Api.GetUserInfo,
    })
    .catch((e) => {
      console.log(e);
      if (e && (e.message.includes("timeout") || e.message.includes("401"))) {
        const userStore = useUserStore();
        userStore.setToken("");
        AuthStorage.setAuthToken("");

        router.push({
          name: LOGIN_PAGE.NAME,
          query: {
            // 传入当前的路由，登录成功后跳转到当前路由
            redirect: router.currentRoute.value.fullPath,
          },
        });
      }
    });
}

export const getUserPermissionByToken = () => {
  return Request.getInstance().send({
    method: "GET",
    url: Api.GetUserPermissionByToken,
  });
};
